﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace Amie
{
    public class ProductManager
    {
        private static string configFilePath = Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "Products.txt";

        public ProductManager()
        {
            //Create default products...
            if (!File.Exists(configFilePath))
                CreateDefaultProducts();
        }

        public ProductInfo GetProductFromConfig()
        {
            var product = System.Configuration.ConfigurationManager.AppSettings["ProductName"];
            return GetProduct(product);
        }

        public List<ProductInfo> Products()
        {
            var fileOutput = File.ReadAllText(configFilePath);
            List<ProductInfo> deserializedProducts = JsonConvert.DeserializeObject<List<ProductInfo>>(fileOutput);
            return deserializedProducts;
        }

        private ProductInfo GetProduct(string webApplicationName)
        {
            var fileOutput = File.ReadAllText(configFilePath);

            List<ProductInfo> deserializedProducts = JsonConvert.DeserializeObject<List<ProductInfo>>(fileOutput);

            foreach (var item in deserializedProducts)
            {
                if (item.WebApplicationName.ToLower() == webApplicationName.ToLower())
                    return item;
            }

            return null;
        }

        private void CreateDefaultProducts()
        {
            //Currently Vendor Specific.  Feel free to change how this works.  These should probably be in some other file.  They will be generated in a json file the first time they are selected.
            ProductInfo uta = new ProductInfo("UTA", "UTA", "Traffic.dll", "Traffic & Alarms Service", "TrafficService.exe", "sqlServer");
            ProductInfo disco = new ProductInfo("Discovery", "Discovery", "Discovery.dll", "Discovery Service", "DiscoveryService.exe", "sqlServer");

            var productList = new List<ProductInfo>();
            productList.Add(uta);
            productList.Add(disco);

            var products = JsonConvert.SerializeObject(productList);

            File.WriteAllText(configFilePath, products);
        }
    }
}
